import React, { useEffect, useState } from 'react';
import { Drawer, Tree } from 'antd';
import { FormattedMessage, useIntl } from 'umi';
import { ProDescriptions } from '@ant-design/pro-components';
import { getMenurule } from '@/services/menurule';
import { getTree } from '@/utils';

type ViewDetailProps = {
  visible: boolean;
  row: Partial<API.RuleListItem>;
  onClose?: () => void;
};

const ViewDetail: React.FC<ViewDetailProps> = (props) => {
  const { visible, row, onClose } = props;
  const intl = useIntl();
  const [treeData, setTreeData] = useState<any[]>([]);
  const getMenuList = async () => {
    const params = { _all: 'ty', type: 'menu,btn,tag' };
    try {
      const { data } = await getMenurule(params);
      const _data = data.data.map((item: API.RuleListItem) => ({
        ...item,
        id: item.id.toString(),
      }));
      setTreeData(getTree(_data || []));
    } catch (err) {}
  };
  useEffect(() => {
    getMenuList();
  }, []);

  const getColumns = (): any[] => {
    return [
      {
        title: <FormattedMessage id="role.name" />,
        dataIndex: 'name',
      },
      {
        title: <FormattedMessage id="public.pid" />,
        dataIndex: 'pname',
      },
      {
        title: <FormattedMessage id="public.status" />,
        dataIndex: 'status',
        valueEnum: {
          0: {
            text: <FormattedMessage id="role.enabled" />,
          },
          1: {
            text: <FormattedMessage id="role.disabled" />,
          },
        },
      },
      {
        title: <FormattedMessage id="role.usernum" />,
        dataIndex: 'usernum',
      },
      {
        title: <FormattedMessage id="role.rule" />,
        dataIndex: 'rules',
        render: (_: any, record: API.RuleListItem) => {
          return record.rules === '*' ? (
            <FormattedMessage id="public.all" />
          ) : (
            <Tree
              checkable
              defaultExpandAll
              checkedKeys={record.rules.split(',')}
              treeData={treeData}
              fieldNames={{ title: 'remark', key: 'id' }}
              selectable={false}
            />
          );
        },
      },
    ];
  };
  const columns = getColumns();
  return (
    <Drawer
      title={intl.formatMessage({ id: 'public.view' }) + intl.formatMessage({ id: 'public.role' })}
      placement="right"
      size="large"
      onClose={onClose}
      open={visible}
      // maskClosable={false}
    >
      <ProDescriptions
        bordered
        // title={row?.name}
        dataSource={{ ...row }}
        columns={columns}
        column={2}
      />
    </Drawer>
  );
};

export default ViewDetail;
